import hashlib
import time
import requests
import json
import pytz
from datetime import datetime  # 確保導入datetime模塊
appKey = "zykj"
secret = "MR333jUBD9gGMGVF7ybqUfJ7XJPVScY5rNWY"

productId = "H6L872Z377"
deviceName = "860761077119333"

channel = 1  # 通道  默认1
state = 1  # 开关状态

def create_token(appKey, secret, ts, params):
    sorted_keys = sorted(params.keys())
    sb = appKey
    for key in sorted_keys:
        sb += key + str(params[key])
    sb += secret
    sb += str(ts)
    codes = sb.encode('utf-8')
    return hashlib.sha1(codes).hexdigest().upper()

def main():
    # 設定香港時區
    hong_kong_tz = pytz.timezone('Asia/Hong_Kong')

    ts = int(datetime.now(hong_kong_tz).timestamp() * 1000)
    print(datetime.now(hong_kong_tz))
    params = {
        "productId": productId,
        "deviceName": deviceName,
        "channel": channel,
        "state": state
    }
    token = create_token(appKey, secret, ts, params)
    headers = {
        "appKey": appKey,
        "token": token,
        "ts": str(ts),
        "Content-Type": "application/json;charset=utf8"
    }
    url = "http://openiot.matezk.cn/openApi/switch"
    response = requests.post(url, headers=headers, data=json.dumps(params))
    body = response.text
    print(headers)
    print(body)
    if response.ok:
        print("操作成功")
    elif response.status_code == 500:
        # 控制失败
        obj = response.json()
        print(obj.get("msg"))
    elif response.status_code == 401:
        # 鉴权失败
        obj = response.json()
        print(obj.get("msg"))
    elif response.status_code == 403:
        # 无操作权限
        obj = response.json()
        print(obj.get("msg"))

if __name__ == "__main__":
    print('start')
    main()